package com.vm.osm.business.controller;

import com.alibaba.druid.util.StringUtils;
import com.google.common.reflect.TypeToken;
import com.vm.osm.business.common.Constants;
import com.vm.osm.business.common.ControllerExceptionHandler;
import com.vm.osm.business.common.ErrCode;
import com.vm.osm.business.common.exception.BusinessException;
import com.vm.osm.business.dto.req.customer.ReqAddCustomer;
import com.vm.osm.business.dto.rsp.HttpRspResult;
import com.vm.osm.business.dto.rsp.customer.Customer;
import com.vm.osm.business.dto.rsp.customer.CustomerPage;
import com.vm.osm.business.dto.rsp.other.RspAreaCode;
import com.vm.osm.business.dto.rsp.other.RspCompanyInfo;
import com.vm.osm.business.dto.rsp.other.RspTypeDict;
import com.vm.osm.business.entity.OsmServerProvider;
import com.vm.osm.business.entity.OsmServerProviderStatus;
import com.vm.osm.business.service.IOsmServerProviderService;
import com.vm.osm.business.service.IOsmServerProviderStatusService;
import com.vm.osm.business.util.ApiCallUtil;
import com.vm.osm.business.util.GsonUtil;
import com.vm.osm.business.util.UserDataUtil;
import com.vm.osm.business.util.UuidUtil;
import io.swagger.annotations.*;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Type;
import java.util.*;

/**
 * 服务商信息
 * Created by zhangshilin on 2018/1/7.
 */
@RestController
@RequestMapping("/v1.0")
@Api(value = "ServiceProviderController", description = "客户相关", tags = {"ServiceProviderController"})
public class ServiceProviderController extends ControllerExceptionHandler {

    private Logger LOG = Logger.getLogger(this.getClass());

    @Autowired
    private IOsmServerProviderService osmServerProviderService;

    @Autowired
    private IOsmServerProviderStatusService serverProviderStatusService;

    @Value("${omp_api_url}")
    private String ompApiUrl;

    @ApiOperation(value = "查询行业大类",notes = "查询行业大类")
    @RequestMapping(value = "get_bigs",method = RequestMethod.GET)
    public List<RspTypeDict> getBigType(
            @ApiParam(required=true, name="page_num", value="分页数") @RequestParam("page_num") Integer page_num,
            @ApiParam(required=true, name="page_size", value="分页大小") @RequestParam("page_size") Integer page_size){
        String getUrl = ompApiUrl+"/omp/v1.0/type_dicts/4/get_tops";
        HttpRspResult httpRspResult = ApiCallUtil.callGet(getUrl);
        if (httpRspResult == null){
            throw new BusinessException("查询行业大类异常");
        }
        if (httpRspResult.getHttp_status() != HttpStatus.SC_OK){
//             rspUcError = GsonUtil.fromJson(httpRspResult.getResponse_str(),RspUcError.class);
//            throw new BusinessException("运营:"+rspUcError.getMessage()+":"+rspUcError.getCause());
            throw new BusinessException("运营OMP-API:"+httpRspResult.getHttp_status());

        }
        Type listType = new TypeToken<ArrayList<RspTypeDict>>(){}.getType();
        List<RspTypeDict> rspTypeDictList = GsonUtil.fromJson(httpRspResult.getResponse_str(),listType);

        return rspTypeDictList;
    }

    @ApiOperation(value = "根据父类查询小类",notes = "根据父类查询小类")
    @RequestMapping(value = "get_second_by_parent_id/{id}",method = RequestMethod.GET)
    public List<RspTypeDict> getSecondByParentId(
            @ApiParam(required=true, name="id", value="父类ID") @RequestParam("id") String id){
        String getUrl = ompApiUrl+"/omp/v1.0/type_dicts/"+id+"/get_subs";
        HttpRspResult httpRspResult = ApiCallUtil.callGet(getUrl);
        if (httpRspResult == null){
            throw new BusinessException("根据父类查询小类异常");
        }
        if (httpRspResult.getHttp_status() != HttpStatus.SC_OK){
            throw new BusinessException("运营OMP-API:"+httpRspResult.getHttp_status());

        }
        Type listType = new TypeToken<ArrayList<RspTypeDict>>(){}.getType();
        List<RspTypeDict> rspTypeDictList = GsonUtil.fromJson(httpRspResult.getResponse_str(),listType);

        return rspTypeDictList;
    }

    @ApiOperation(value = "获取省份列表信息",notes = "获取省份列表信息")
    @RequestMapping(value = "/provinces",method = RequestMethod.GET)
    public List<RspAreaCode> getProvinces(){
        String getUrl = ompApiUrl+"/omp/v1.0/areas/provinces";
        HttpRspResult httpRspResult = ApiCallUtil.callGet(getUrl);
        if (httpRspResult == null){
            throw new BusinessException("获取省份列表信息异常");
        }
        if (httpRspResult.getHttp_status() != HttpStatus.SC_OK){
            throw new BusinessException("运营OMP-API:"+httpRspResult.getHttp_status());

        }
        Type listType = new TypeToken<ArrayList<RspAreaCode>>(){}.getType();
        List<RspAreaCode> rspTypeDictList = GsonUtil.fromJson(httpRspResult.getResponse_str(),listType);
        return rspTypeDictList;
    }

    @ApiOperation(value = "根据省份编码获取城市列表信息",notes = "根据省份编码获取城市列表信息")
    @RequestMapping(value = "/citys/{org_code}",method = RequestMethod.GET)
    public List<RspAreaCode> getCitysById(
            @ApiParam(required=true, name="org_code", value="省份组织编码") @RequestParam("org_code") String orgCode){
        String getUrl = ompApiUrl+"/omp/v1.0/areas/"+orgCode+"/citys";
        HttpRspResult httpRspResult = ApiCallUtil.callGet(getUrl);
        if (httpRspResult == null){
            throw new BusinessException("获取省份列表信息异常");
        }
        if (httpRspResult.getHttp_status() != HttpStatus.SC_OK){
            throw new BusinessException("运营OMP-API:"+httpRspResult.getHttp_status());

        }
        Type listType = new TypeToken<ArrayList<RspAreaCode>>(){}.getType();
        List<RspAreaCode> rspTypeDictList = GsonUtil.fromJson(httpRspResult.getResponse_str(),listType);
        return rspTypeDictList;
    }

    @ApiOperation(value = "新增客户",notes = "新增客户，未根据公司名称与营业执照编码查找到的情况下使用")
    @ApiImplicitParam(name = "reqAddCustomer",value = "新增客户参数",required = true,dataType = "ReqAddCustomer")
    @RequestMapping(value = "/customer/addCustomer",method = RequestMethod.POST)
    public void addCustomer(@RequestBody ReqAddCustomer reqAddCustomer, HttpServletRequest request){
        String enterpriseId = UserDataUtil.getUserSelectedEnterpriseId(request);
        OsmServerProvider osmServerProvider = new OsmServerProvider();
        osmServerProvider.setUpdateTime(new Date());
        osmServerProvider.setCreateTime(new Date());
        osmServerProvider.setId(UuidUtil.getRandomUuid());
        osmServerProvider.setStatus(new String("00001"));
        osmServerProvider.setCompanyId(enterpriseId);
        osmServerProvider.setLinkMan(reqAddCustomer.getLink_man());
        osmServerProvider.setLinkPhone(reqAddCustomer.getLink_phone());
        osmServerProvider.setFirstIndustryId(reqAddCustomer.getFirst_industry_id());
        osmServerProvider.setSecondIndustryId(reqAddCustomer.getSecond_industry_id());
        osmServerProvider.setLocation(reqAddCustomer.getDetail());
        osmServerProvider.setProviderCode(reqAddCustomer.getProvider_code());
        osmServerProvider.setProviderName(reqAddCustomer.getProvider_name());
        osmServerProvider.setRemark(reqAddCustomer.getRemark());
        osmServerProvider.setAreaInfo(reqAddCustomer.getArea_info());
        osmServerProvider.setIndustryInfo(reqAddCustomer.getIndustry_info());
        int res = osmServerProviderService.insert(osmServerProvider);

        if (res == 0){
            throw new BusinessException(ErrCode.ADD_DATA_FAIL.toString());
        }
    }


    @ApiOperation(value = "分页查询客户",notes = "分页查询客户，获取当前客户列表")
    @RequestMapping(value = "/customer/get_customers_by_page",method = RequestMethod.GET)
    public CustomerPage queryProvidersPageByCond(
            @ApiParam(required=true, name="page_num", value="分页数") @RequestParam("page_num") Integer pageNum,
            @ApiParam(required=true, name="page_size", value="分页大小") @RequestParam("page_size") Integer pageSize,
            @ApiParam(name="key_word", value= "客户名称/代码/联系人") @RequestParam(value = "key_word",required = false) String keyWord){
        return osmServerProviderService.queryProvidersPageByCond(pageNum,pageSize,keyWord);
    }

    @ApiOperation(value = "运维客户详情接口",notes = "运维客户详情接口")
    @RequestMapping(value = "/customer/detail/{id}",method = RequestMethod.GET)
    public Customer getOsmCustomerById(@ApiParam(required=true, name="id", value="客户ID") @PathVariable("id") String id){
        Customer customer = osmServerProviderService.queryProvidersById(id);
        return customer;
    }

    @ApiModelProperty(value = "客户关系更新",notes = "1解除关系2删除3申请为客户4恢复为客户")
    @RequestMapping(value = "/customer/handle_relation",method = RequestMethod.PUT)
    public void handleCustomerRelationShip(@ApiParam(required = true,name = "id",value = "id") @RequestParam("id") String id,
                                           @ApiParam(required = true,name = "status",value = "status") @RequestParam("status") Integer status){

        LOG.info("客户关系更新");
        osmServerProviderService.handleCustomerRelationShip(id,"",status);
    }


    @ApiOperation(value = "根据信息获取服务商信息,调用运营平台接口",notes = "根据信息获取服务商信息。(名称，社会编码，联系人等)")
    @RequestMapping(value = "/customer/get_by_cond",method = RequestMethod.GET)
    public List<RspCompanyInfo> getByCond(
            @ApiParam( name="key_word", value="企业名称、企业编码、ID") @RequestParam(value = "key_word",required = false) String keyWord){
        String getUrl = ompApiUrl+"/omp/v1.0/companys/get_by_content";
        if(!StringUtils.isEmpty(keyWord)){
            getUrl+="?content="+keyWord;
        }
        HttpRspResult httpRspResult = ApiCallUtil.callGet(getUrl);
        if (httpRspResult == null){
            throw new BusinessException("根据信息获取服务商信息异常");
        }
        if (httpRspResult.getHttp_status() != HttpStatus.SC_OK){
            throw new BusinessException("运营OMP-API:"+httpRspResult.getHttp_status());
        }
        Type listType = new TypeToken<ArrayList<RspCompanyInfo>>(){}.getType();
        List<RspCompanyInfo> rspTypeDictList = GsonUtil.fromJson(httpRspResult.getResponse_str(),listType);
        return rspTypeDictList;
    }

    @ApiOperation(value = "根据主键获取企业信息",notes = "根据主键获取企业信息")
    @RequestMapping(value = "/customer/get_by_id/{id}",method = RequestMethod.GET)
    public RspCompanyInfo getCompanyInfoById(@ApiParam(required=true, name="id", value="系统编号") @PathVariable("id") String id){
        String getUrl = ompApiUrl+"/omp/v1.0/companys/"+id;
        HttpRspResult httpRspResult = ApiCallUtil.callGet(getUrl);
        if (httpRspResult == null){
            throw new BusinessException("根据信息获取服务商信息异常");
        }
        if (httpRspResult.getHttp_status() != HttpStatus.SC_OK){
            throw new BusinessException("运营OMP-API:"+httpRspResult.getHttp_status());
        }
        RspCompanyInfo rspCompanyInfo = GsonUtil.fromJson(httpRspResult.getResponse_str(),RspCompanyInfo.class);
        return rspCompanyInfo;
    }

    @ApiOperation(value = "获取客户列表",notes = "获取客户列表，分配运维时使用")
    @RequestMapping(value = "/customer/get_by_page",method = RequestMethod.GET)
    public CustomerPage getCustomersByPage(HttpServletRequest request,
                                   @ApiParam( name="name", value="客户名称") @RequestParam(value = "name",required = false) String name,
                                   @ApiParam( name="location", value="所在地") @RequestParam(value = "location",required = false) String location,
                                   @ApiParam(required=true, name="page_num", value="分页数") @RequestParam("page_num") Integer pageNum,
                                   @ApiParam(required=true, name="page_size", value="分页大小") @RequestParam("page_size") Integer pageSize){
        LOG.info("获取客户列表");
        String mac = request.getHeader(Constants.MAC_KEY);
        //企业编号
        String enterpriseId = UserDataUtil.getUserSelectedEnterpriseId(request);
        return osmServerProviderService.queryByPage(pageNum,pageSize,"0",name,location);

    }

//    @ApiOperation(value = "初始化客户状态字典表",notes = "初始化客户状态字典表")
//    @RequestMapping(value = "/customer/initStatus",method = RequestMethod.POST)
    public void initStatus(){
        OsmServerProviderStatus status1 = new OsmServerProviderStatus();
        status1.setStatus(new Byte("1"));
        status1.setCreateTime(new Date());
        status1.setSimpleDesc("帐号未开通");
        status1.setId("00001");
        OsmServerProviderStatus status2 = new OsmServerProviderStatus();
        status2.setStatus(new Byte("1"));
        status2.setCreateTime(new Date());
        status2.setSimpleDesc("已通过");
        status2.setId("00002");
        OsmServerProviderStatus status3 = new OsmServerProviderStatus();
        status3.setStatus(new Byte("1"));
        status3.setCreateTime(new Date());
        status3.setSimpleDesc("对方解除");
        status3.setId("00003");
        OsmServerProviderStatus status4 = new OsmServerProviderStatus();
        status4.setStatus(new Byte("1"));
        status4.setCreateTime(new Date());
        status4.setSimpleDesc("己方解除");
        status4.setId("00004");
        OsmServerProviderStatus status5 = new OsmServerProviderStatus();
        status5.setStatus(new Byte("1"));
        status5.setCreateTime(new Date());
        status5.setSimpleDesc("待验证");
        status5.setId("00005");
        serverProviderStatusService.insert(status1);
        serverProviderStatusService.insert(status2);
        serverProviderStatusService.insert(status3);
        serverProviderStatusService.insert(status4);
        serverProviderStatusService.insert(status5);
    }


}
